package com.xyz.controller;

import com.xyz.dao.UserDao;
import com.xyz.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    private UserDao userDao;

    @GetMapping({"/index","/"})
    public Object index(Model model){
        model.addAttribute("xyz","哈喽Shiro");
     return "index";
    }

    @GetMapping("/user/add")
    public Object add(){
        return "user/add";
    }
    @GetMapping("/user/update")
    public Object updata(){
        return "user/updata";
    }
    @RequestMapping("/tologin")
    public Object tologin(){
        return "login";
    }

    //未授权跳转的页面
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权不得访问";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        //执行登录方法，没有异常就OK了
        try {
            subject.login(usernamePasswordToken);
            //该session不是servlet的Session
             Session session =subject.getSession();
             session.setAttribute("user",(User)subject.getPrincipal());
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }
}
